package com.gsnd.gsnd21study.web;

import com.gsnd.gsnd21study.entity.Student;
import com.gsnd.gsnd21study.exception.ServiceException;
import com.gsnd.gsnd21study.mapper.StudentMapper;
import com.gsnd.gsnd21study.utils.Result;
import com.gsnd.gsnd21study.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {
    // 调用dao层来实现
    @Autowired
    private StudentMapper studentMapper;

    // 查询单个
    @GetMapping("/{sno}")
    public Result<Student> getStudentById(@PathVariable Long sno) throws ServiceException {

        // 手动创造一个系统的运行时异常
        // int i = 10 / 0;

        // 手动抛出一个自定义异常
//        if(1>0){
//            throw new ServiceException(ResultCode.SYSTEM_INNER_ERROR);
//        }

        Student student = studentMapper.selectById(sno);
        return Result.success(student);
    }

    // 根据条件查询
    @GetMapping("/condition")
    public Result<List<Student>> getStudentByCondition(@RequestParam String name,
                                                       @RequestParam Integer age,
                                                       @RequestParam String gender){
        List<Student> list = studentMapper.selectByCondition(name, age, gender);
        return Result.success(list);
    }


    // 新增（限定添加学生的时候对数据进行保密，使用post请求）
    @PostMapping("/")
    public Result<String> saveStudent(@RequestBody Student student){
        studentMapper.insert(student);
        return Result.success("添加成功");
    }

    // 条件更新
    @PutMapping("/")
    public Result<?> editStudent(@RequestBody Student student){
        studentMapper.update(student);
        return Result.success();
    }

    // 删除单个
    @DeleteMapping("/{sno}")
    public Result<?> removeStudentById(@PathVariable Long sno){
        studentMapper.deleteById(sno);
        return Result.success();
    }

    // 批量删除
    @DeleteMapping("/batch")
    public Result<?> removeBatch(@RequestBody List<Long> ids){
        studentMapper.deleteBatch(ids);
        return Result.success();
    }
}
